package com.camartsApp.Util;

import com.drew.imaging.ImageMetadataReader;
import com.drew.metadata.*;
import com.drew.metadata.exif.*;
import com.drew.metadata.exif.GpsDirectory;
import com.drew.lang.GeoLocation;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Component
public class PhotoMetadataUtil {

    public static Map<String, Object> extractMetadata(MultipartFile file) {
        Map<String, Object> metadataMap = new HashMap<>();
        try (InputStream inputStream = file.getInputStream()) {
            Metadata metadata = ImageMetadataReader.readMetadata(inputStream);

            // 1. 拍摄时间
            ExifSubIFDDirectory exif = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);
            if (exif != null) {
                metadataMap.put("takenAt", exif.getDateOriginal()); // java.util.Date 类型
                metadataMap.put("aperture", exif.getDescription(ExifSubIFDDirectory.TAG_FNUMBER));
                metadataMap.put("shutter", exif.getDescription(ExifSubIFDDirectory.TAG_EXPOSURE_TIME));
                metadataMap.put("iso", exif.getDescription(ExifSubIFDDirectory.TAG_ISO_EQUIVALENT));
                metadataMap.put("focalLength", exif.getDescription(ExifSubIFDDirectory.TAG_FOCAL_LENGTH));
            }

            // 2. 相机设备信息
            ExifIFD0Directory ifd0 = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
            if (ifd0 != null) {
                metadataMap.put("device", ifd0.getDescription(ExifIFD0Directory.TAG_MODEL));
            }

            // 3. GPS 信息
            GpsDirectory gps = metadata.getFirstDirectoryOfType(GpsDirectory.class);
            if (gps != null) {
                GeoLocation location = gps.getGeoLocation();
                if (location != null) {
                    metadataMap.put("latitude", location.getLatitude());
                    metadataMap.put("longitude", location.getLongitude());
                }
            }

        } catch (Exception e) {
            System.out.println("读取照片元数据失败：" + e.getMessage());
        }
        return metadataMap;
    }
}